﻿using LuckyShell.ShellValues;

namespace LuckyShell.ShellOrders;

public class IfOrder(IfBlock ifBlock, List<IfBlock>? elifBlock, BlockOrder? elseBlockStatement)
    : ShellOrder
{
    private IfBlock IfBlock { get; set; } = ifBlock;

    private List<IfBlock>? ElifBlock { get; set; } = elifBlock;

    private BlockOrder? ElseBlockStatement { get; set; } = elseBlockStatement;

    public void Run(ref VariateManager manager)
    {
        var r = true;
        manager.AddChildren();
        IfBlock.Run(ref manager, ref r);
        manager.RemoveChildren();
        if (ElifBlock is not null)
        {
            foreach (var oldIf in ElifBlock)
            {
                manager.AddChildren();
                oldIf.Run(ref manager, ref r);
                manager.RemoveChildren();
            }
        }

        if (ElseBlockStatement is null || !r) return;
        manager.AddChildren();
        ElseBlockStatement.Run(ref manager);
        manager.RemoveChildren();
    }
}

public class IfBlock(ShellValue expr, BlockOrder blockOrder) : ShellOrder
{
    public void Run(ref VariateManager manager)
    {
    }

    private ShellValue Expr { get; set; } = expr;

    private BlockOrder BlockOrder { get; set; } = blockOrder;

    public void Run(ref VariateManager Manager, ref bool r)
    {
        if (r == false) return;
        var exprValue = Expr.GetValue(ref Manager);
        if (exprValue is not BoolValue value) return;
        if (!(bool)value.GetValue(ref Manager)) return;
        BlockOrder.Run(ref Manager);
        r = false;
    }
}